/*
 * jQuery functions used in the page to manage images. 
 */

/* We dynamically adapt the  UI size to the window*/
var window_height;
var content_height;
var djips_height;
var content_width;

var right_menu_content;
var selected_image;

/* Spray stuff */
var spray = false;
var spraying = false;
var spray_mode = 'mark';
var sprayed_mark = 0;
var sprayed_color = -1;
var sprayed_elements = [];

update_ui_size = function(){
    window_height = $(window).height();
    content_height = $('#content').height();
    djips_height = $('#djips').height();
    content_width = $('#content').width();

    /* Update content heigth */
    new_content_height = window_height - (djips_height - content_height + 30);
    if (new_content_height < 500) {
        new_content_height = 500;
    }
    
    $('#content').css({'height': new_content_height + 'px'});

    $('#images_ui_left_menu').css(
       {'height': (new_content_height - 23) + 'px'});

    /* With a long list of folders, a slider appears on the right and
      the preview gets screwed. So we limitate the height of the folder list
      and the slider will just appear on this element. */
    $('#folder_choser').css(
       {'height': (new_content_height - 300) + 'px'});

    $('#images_ui_main').css(
       {'height': (new_content_height - 23) + 'px',
        'width': (content_width - 400) + 'px'});
    
    $('#images_ui_right_menu').css(
       {'height': (new_content_height - 23) + 'px'});
    
}


/* Gets the Ajax optimized UI and replaces it in the page. */
load_full_ui = function() {
    var ui_loaded = false;    
    ui = $.ajax({url: admin_base_url + '/djips_common/ajax/images_ui/',
                    async: false,
                    success: function(){ui_loaded = true}}).responseText;

    /* Unable to load UI - use the old one. */
    if (!ui_loaded) {
        return false;
    }    
    /* Remove default UI */
    $('#update_images_form').remove();
    $('#update_images_filesystem').remove();

    /* Adds the new one */
    $('#content').append(ui);
    $('#content').css({'padding': '0px'});

    make_star_widget('.mark_widget_container');    
    make_color_widget('.color_widget_container');
    
    return true;    
}
    
/* Fills the main div with images */
update_main = function(){
    /* First apply visual selector */
    $('li.current').removeClass('current')
    $(this).addClass('current');

    /* We find the link contained in the item and the id of the folder */
    folder_id = $(this).find('a').attr('href');
    
    url = admin_base_url + '/djips_common/ajax/get_images/' + folder_id + '/'
    $('#images_ui_main').load(url, {}, function(){
        /* If the selected image has disapeared, we refresh the right panel */
        previous_selected = $('#' + selected_image);
        
        if (previous_selected.length == 0) {
            $('#images_ui_right_menu').html(right_menu_content);
            $('#preview img').attr('src', images_folder + '1x1.gif')
            selected_image = 'none';
        }
        else {
            previous_selected.addClass('selected');
        }
    });

    /* We turn of spray mode */
    deactivate_spray()
    
    return false;
}
    
/* Updates the preview and the property tab */
load_right_panel = function(image_id){
    url = admin_base_url + '/djips_common/ajax/get_image_properties_form/' +
    image_id + '/'
    image_properties = $.ajax({url: url,
                               async: false}).responseText;
    
    $('#preview div img').attr('src', image_url);
    $('#images_ui_right_menu').html(image_properties);

    make_star_widget('.mark_widget_container');    
    make_color_widget('.color_widget_container');
    
    /* When the user clicks save, the dia of the image is reloaded
     * with new values.
     * An overlay appears brifly */
    $('#image_properties_form .valid').click(function(){
        var image_id = $(this).attr('rel');
        $(this).parent().parent().ajaxSubmit(
            {'success': function(responseText, statusText){
                    $('#image_' + image_id).replaceWith(responseText);
                    hover = $('#image_' + image_id + ' .dia_overlay');
                    hover.css({'display': 'block',
                               'background': '#11f215',
                                'opacity': '0.5', 
                                'filter': 'alpha(opacity=50)'});
                    hover.fadeOut(1000, function() {
                            hover.css({'background': 'none'});
                        });
		    $('#image_' + image_id).addClass('selected');
                }});
        
        return false;        
    });

    /* When the user clicks cancel, we reload the panel */
    $('#image_properties_form .cancel').click(function(){
        load_right_panel(image_id);            
    });
    
}

/* Show the image in the preview and the form in the right panel */
load_image = function() {
    div_id = $(this).attr('id').split('_');
    image_id = div_id[1];

    /* Change class of the current image so the user knows
     * which image he is working on. */
    $('.dia.selected').removeClass('selected');
    $(this).addClass('selected');
    selected_image = this.id;    
    
    url = admin_base_url + '/djips_common/ajax/get_full_image_url/' +
    image_id + '/'
    image_url = $.ajax({url: url,
                        async: false}).responseText;

    load_right_panel(image_id);
}

/* Changes options for spraying */
switch_spray_options = function(){
    spray_mode = $(this).attr('value');
    
    if (spray_mode == 'mark') {
        $('.commands .color_widget_container').fadeOut('fast', function(){
                $('.commands .mark_widget_container').fadeIn();});
    }
    else {
        $('.commands .mark_widget_container').fadeOut('fast', function(){
                $('.commands .color_widget_container').fadeIn();});
    }
}

apply_spray = function(overlay){
    image_id = $(overlay).parent().attr('id').split('_')[1];

    for (i in sprayed_elements) {
        if (sprayed_elements[i] == image_id) {
            // Already sprayed - nothing needed.
            return;
        }
    }
    sprayed_elements.push(image_id);
    
    
    if (spray_mode == 'mark') {
        value = sprayed_mark;
    }
    if (spray_mode == 'color') {
        value = sprayed_color;
    }

    url = admin_base_url + '/djips_common/ajax/spray/' + image_id +
    '/?mode=' + spray_mode + '&value=' + value;

    new_content = $.ajax({url: url,
                          async: false}).responseText;
    
    $(overlay).next().replaceWith(new_content);
}

/**/
activate_spray = function(){
    spray = true;

    $('.spray').addClass('active');

    overlay = $('.dia_overlay');
    overlay.show();
    attach_overlay();
}
    
attach_overlay = function(){
    overlay = $('.dia_overlay');
    overlay.mousedown(function(){
            sprayed_mark = $('.commands .mark_widget_container input').
                attr('value');
            sprayed_color = $('.commands .color_widget_container input').
                attr('value');

            spraying = true;
            apply_spray(this);

            return false;
        });
    
    overlay.mouseenter(function(){
            if (spraying) {
                apply_spray(this);
            }
        });
    
    $(window).mouseup(function(){
            spraying = false;
            sprayed_elements = [];
        });
}

deactivate_spray = function(){
    spray = false;
    $('.spray').removeClass('active');

    $('.dia_overlay').hide();    
}    
    
$('document').ready(function() {    
    if (!load_full_ui()){
        return;
    }

    $('#content').css({'position': 'relative'});    
    $(window).resize(update_ui_size);
    update_ui_size();

    /* We save the original value of the right panel. */
    right_menu_content = $('images_ui_right_menu').html()
    
    $('li.djips_plainfilesystem').click(update_main);

    $('.dia').live('click', load_image);
    $('.accordion_head').live('click', accordion);

    $('#preview img').live('click', function(){
            img_lightbox($(this).attr('src'));
    });

    /* Stuff about spray */
    $('#spray_selector').change(switch_spray_options);

    $('.spray').click(function(){
            if (spray) {
                deactivate_spray();
            } else {
                activate_spray();
            }            
            return false;
        });    
});
